package com.practice.car.cardataapp.util;

import java.io.IOException;
import java.util.Date;

import cn.hutool.*;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.practice.car.cardataapp.entity.Token;

import javax.servlet.http.HttpServletResponse;

/**
 * car-data-app project
 *
 * @author 陈春幸
 * @date 2020/9/5 0005
 */
public class TokenUtil {

	/*
	 * 过期时间12小时
	 * */
	private static final long EXPIRE_TIME = 1000 * 60 * 60 * 12;
	/*
	 * 私钥
	 * */
	private static final String TOKEN_SECRET = "hfdasdfjhahfahfa";
	private static final byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), TOKEN_SECRET.getBytes()).getEncoded();
	private static final SymmetricCrypto symmetricCrypto = new SymmetricCrypto(SymmetricAlgorithm.AES, key);

	public static R getRWithToken(Token token) {

		//String expireDate=(new Date(System.currentTimeMillis()+EXPIRE_TIME)).toString();
		String tokenString = token.toString();
		String encryptedToken = symmetricCrypto.encryptHex(tokenString);
		R r = R.create();
		r.put("cartoken", encryptedToken);
		return r;
	}


	public static boolean verifyToken(HttpServletResponse response,String tokenString) throws IOException {
		// TODO: 2020/9/6 0006

		String decryptedTokenString = symmetricCrypto.decryptStr(tokenString, CharsetUtil.CHARSET_UTF_8);
		String[] tokenDetail = decryptedTokenString.split("=");
		Token token = new Token();
		token.setMsg(tokenDetail[0]);
		token.setExpireTime(tokenDetail[1]);
		//对token信息进行判断？？需不需要
        //没有token，去登陆
        if(tokenString == null){
            response.sendRedirect("/login");
            return false;
        }

        //无效token，去登陆
        if(token == null){
            response.sendRedirect("/login");
            return false;
        }

        //过期token，去登陆
        if(TokenUtil.getExpiredAt(token).before(new Date())){
            response.sendRedirect("/login");
            return false;
        }

        return token.getMsg()!=null&&token.getMsg().contains("系统管理员");
	}

	public static Date getExpiredAt(Token token) {
		// TODO: 2020/9/7 0007

		return new Date(Long.valueOf(token.getExpireTime()));
	}

	public static long getExpireTime() {
		return EXPIRE_TIME;
	}
}
